from scapy.all import *
import random
import time
import json


def generate_game_data():

    game_data = {
        "player_id": random.randint(1, 1000),
        "position": {"x": random.random(), "y": random.random(), "z": random.random()},
        "health": random.randint(1, 100),
        "inventory": {"coins": random.randint(0, 500), "items": random.randint(0, 10)},
    }
    return json.dumps(game_data)


def generate_packet(dst_ip, dst_port, payload):
    src_ip = ".".join(str(random.randint(0, 255)) for _ in range(4))
    #src_ip = "192.168.1.66"
    src_port = random.randint(1024, 65535)
    seq = random.randint(0, 4294967295)

    packet = IP(dst=dst_ip,src=src_ip) / TCP(dport=dst_port, sport=src_port, seq=seq) / Raw(load=payload)
    return packet


def send_packets(dst_ip, dst_port, duration=100, interval=0.05, data_size=200):

    start_time = time.time()
    while time.time() - start_time < duration:
        time.sleep(0.01)
        game_data = generate_game_data()
        game_data = game_data[:data_size].ljust(data_size, ' ')
        packet = generate_packet(dst_ip, dst_port, game_data)
        send(packet)
        time.sleep(interval)


def send_to_multiple_servers(servers):

    for server in servers:
        ip, port = server
        print(f"Sending packets to {ip}:{port}")
        send_packets(ip, port, duration=100, interval=0.2, data_size=200)   # 可以修改调整

servers = [
    ("192.168.1.1", 8888),
    # 修改 & 添加
]


send_to_multiple_servers(servers)
